package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.RegisterDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.CodeGeneratorUtil;
import com.heima.utils.common.MD5Utils;
import com.heima.utils.common.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.用户登录
        if(StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPassword())){
            //1.1 查询用户信息
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //1.2验证密码
            String salt = apUser.getSalt();
            String password = apUser.getPassword();
            String digest = DigestUtils.md5DigestAsHex((salt + dto.getPassword()).getBytes());
            if(!password.equals(digest)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            //2.游客登录
            String token = AppJwtUtil.getToken(0l);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
    /**
     * 获取验证码
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getCode(RegisterDto dto) {
        String phone = dto.getPhone();
        if(StringUtils.isBlank(phone)) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号为空");
        String code = CodeGeneratorUtil.getFourLengthCode();
        SendSms.sendMsg(phone,code);
        redisTemplate.opsForValue().set(phone,code,2*60l, TimeUnit.SECONDS);
        return ResponseResult.okResult("发送成功");
    }
    /**
     * 校验验证码
     * @param dto
     * @return
     */
    @Override
    public ResponseResult checkCode(RegisterDto dto) {
        if(dto==null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        String code = dto.getCode();
        String phone = dto.getPhone();

        if(StringUtils.isBlank(code) || StringUtils.isBlank(phone))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号或者验证码为空");

        String oldCode = (String) redisTemplate.opsForValue().get(phone);

        if(oldCode==null) return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE,"验证码已过期");

        if(!code.equals(oldCode)) return ResponseResult.errorResult(
                AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"验证码不正确");
        redisTemplate.delete(phone);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 注册
     * @param dto
     * @return
     */
    @Override
    public ResponseResult register(RegisterDto dto) {

        try {
            if(dto==null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            String username = dto.getUsername();
            String passwordStr = dto.getPassword();
            //手机号由前端发过来
            String phone = dto.getPhone();
            if(phone==null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号不存在");
            if(StringUtils.isBlank(username) || StringUtils.isBlank(passwordStr))
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码不存在");
            String salt = UUID.randomUUID().toString().replace("-", "");
            String password = MD5Utils.encodeWithSalt(passwordStr, salt);
            ApUser apUser = new ApUser();
            apUser.setName(username);
            apUser.setPassword(password);
            apUser.setPhone(phone);
            apUser.setSalt(salt);
            apUser.setCreatedTime(new Date());
            this.save(apUser);
        } catch (Exception e) {
            //用户已经不在
            new CustomException(AppHttpCodeEnum.DATA_EXIST);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
